<script lang="ts" setup>
  import { ref, computed, watch, reactive } from 'vue';
  import {
    Tabs,
    TabPane,
    Card,
    Button,
    Modal,
    Message,
    Form,
    FormItem,
    Input,
    Textarea,
    Select,
    Option,
    Space,
  } from '@arco-design/web-vue';
  import { ApiManageList } from '/@/components/ApiManageList';
  import type { ArticleColumnRecord } from '/@/api/model/recommendModel';
  import { querySpColumnPage, deleteSpColumn, addSpColumn } from '/@/api/column';
  import type { SpColumnRecord } from '/@/api/model/columnModel';
  import { useRouter } from 'vue-router';
  import { PageEnum } from '/@/enums/pageEnum';
  import { Upload } from '/@/components/Upload';
  import type { FileItem } from '/@/components/Upload';
  import { isEmpty } from 'lodash-es';
  import { queryArticleColumnList } from '/@/api/recommend';

  const router = useRouter();
  const apiManageList = ref();
  const isUpdate = ref(false);
  const modelVisible = ref(false);
  const formRef = ref();
  type FormRecord = Pick<SpColumnRecord, 'name' | 'desc' | 'cover' | 'column_id'>;
  const form = reactive<FormRecord>({
    name: '',
    desc: '',
    cover: '',
    column_id: undefined!,
  });
  const fileList = ref<FileItem[]>([]);
  const toAdd = () => {
    formRef.value.resetFields();
    isUpdate.value = false;
    modelVisible.value = true;
  };
  const toEdit = ({ item }: { item: SpColumnRecord }) => {
    formRef.value.resetFields();
    isUpdate.value = true;
    Object.assign(form, item);
    modelVisible.value = true;
  };
  const onDelete = ({ item, reload }: { item: SpColumnRecord; reload: PromiseFn }) => {
    Modal.warning({
      title: '删除专栏',
      content: '删除专栏后不可恢复，确定删除吗？',
      onOk: async () => {
        try {
          await deleteSpColumn(item.id);
          Message.success('删除成功');
          reload();
        } catch (err) {
          Message.error((err as Error).message || '删除失败');
        }
      },
    });
  };
  const toEditContent = ({ item }: { item: SpColumnRecord }) => {
    router.push(`/creator/content/sp_column/edit/${item.id}`);
  };
  const callActions = () => {
    const actions = [{ label: '管理内容', onClick: toEditContent }];
    actions.push(
      ...[
        { label: '修改介绍', onClick: toEdit },
        { label: '删除', onClick: onDelete },
      ],
    );
    return actions;
  };
  const getSpColumnEditModalTitle = computed(() => {
    return isUpdate.value ? '修改专栏' : '新建专栏';
  });
  const reload = () => {
    apiManageList.value?.forEach((item) => item.reload());
  };
  const onSubmit = async () => {
    const errors = await formRef.value.validate?.();
    if (!isEmpty(errors)) {
      return false;
    }
    const result = await addSpColumn({
      name: form.name,
      desc: form.desc,
      cover: form.cover,
      column_id: form.column_id as unknown as number,
    });
    if (result.id) {
      reload();
    }
  };
  const articleColumnListRef = ref<ArticleColumnRecord[]>([]);

  (async () => {
    const data = await queryArticleColumnList();
    articleColumnListRef.value = data;
  })();

  // 标签页
  const activeKey = ref('');
  watch(
    router.currentRoute,
    ({ path }) => {
      activeKey.value = path;
    },
    { immediate: true },
  );
  watch(activeKey, (key) => {
    if (key !== router.currentRoute.value.path) {
      router.push(key);
    }
  });

  // 文章状态
  const statusKey = ref('');
  const statusTabs = computed(() => {
    return [
      { title: '全部', key: 'all', api: querySpColumnPage },
      // { title: '已发布', key: 'published', api: queryPublishedArticlePage },
      // { title: '已下架', key: 'rejected', api: queryPublishedButRejectedArticlePage },
    ];
  });
  const queryStatus = computed(() => {
    const { status } = router.currentRoute.value.query;
    return Array.isArray(status) ? status[0] : status;
  });
  watch(
    router.currentRoute,
    () => {
      if (router.currentRoute.value.path !== PageEnum.CREATOR_CONTENT_SP_COLUMN) return;
      if (queryStatus.value && ['all', 'published', 'rejected'].includes(queryStatus.value)) {
        statusKey.value = queryStatus.value;
      } else {
        router.push({ query: { status: 'all' } });
      }
    },
    { immediate: true },
  );
  watch(statusKey, (status) => {
    if (router.currentRoute.value.path !== PageEnum.CREATOR_CONTENT_SP_COLUMN) return;
    if (status !== queryStatus.value) {
      router.push({ query: { status } });
    }
  });

  watch(fileList, () => {
    form.cover = fileList.value?.[0]?.url || '';
  });
</script>

<template>
  <Card>
    <Tabs class="mb-[14px]" hoverable v-model:activeKey="activeKey" lazyLoad destroyOnHide>
      <TabPane title="专栏" :key="PageEnum.CREATOR_CONTENT_SP_COLUMN">
        <Tabs lazyLoad v-model:activeKey="statusKey" type="text" destroyOnHide>
          <TabPane v-for="item in statusTabs" :key="item.key" :title="item.title">
            <ApiManageList
              ref="apiManageList"
              :api="item.api"
              :params="{ status: item.key }"
              :getLink="(item) => `/sp_column/${item.id}`"
              :actions="callActions"
              :fieldNames="{
                title: 'name',
              }"
            >
              <template #desc="{ data }: { data: SpColumnRecord }">
                <Space :size="[24, 0]" class="text-gray-500">
                  <template #split>|</template>
                  <span>{{ data.updateTime }}</span>
                  <Space :size="[12, 0]">
                    <template #split>·</template>
                    <span>文章数{{ data.article_num }}</span>
                    <span>订阅人数{{ data.subscribe_num }}</span>
                  </Space>
                </Space>
              </template>
            </ApiManageList>
          </TabPane>
        </Tabs>
      </TabPane>
    </Tabs>
    <Button class="absolute right-[30px] top-[12px]" type="primary" @click="toAdd">新建专栏</Button>
    <Modal
      v-model:visible="modelVisible"
      :title="getSpColumnEditModalTitle"
      :on-before-ok="onSubmit"
    >
      <Form :model="form" ref="formRef">
        <FormItem field="name" label="专栏名称" label-col-flex="80px" required>
          <Input v-model="form.name" :maxLength="50" showWordLimit />
        </FormItem>
        <FormItem field="desc" label="专栏简介" label-col-flex="80px" required>
          <Textarea v-model="form.desc" :maxLength="150" showWordLimit />
        </FormItem>
        <FormItem field="column_id" label="栏目" label-col-flex="80px" required>
          <Select v-model="form.column_id">
            <Option v-for="item in articleColumnListRef" :key="item.id" :value="item.id">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="文章封面" label-col-flex="80px">
          <Upload v-model:file-list="fileList" />
        </FormItem>
      </Form>
    </Modal>
  </Card>
</template>
